package interpreter

var GlobalSymbolTable = NewSymbolTable(nil)

// 会自动运行的代码
func init() {
	GlobalSymbolTable.Set("null", Null)
	GlobalSymbolTable.Set("false", False)
	GlobalSymbolTable.Set("true", True)
	GlobalSymbolTable.Set("math_pi", MathPi)
	GlobalSymbolTable.Set("print", Print)
	GlobalSymbolTable.Set("print_ret", PrintRet)
	GlobalSymbolTable.Set("input", Input)
	GlobalSymbolTable.Set("input_int", InputInt)
	GlobalSymbolTable.Set("clear", Clear)
	GlobalSymbolTable.Set("cls", Clear)
	GlobalSymbolTable.Set("is_num", IsNumber)
	GlobalSymbolTable.Set("is_str", IsString)
	GlobalSymbolTable.Set("is_list", IsList)
	GlobalSymbolTable.Set("is_fun", IsFunction)
	GlobalSymbolTable.Set("append", Append)
	GlobalSymbolTable.Set("pop", Pop)
	GlobalSymbolTable.Set("extend", Extend)
	GlobalSymbolTable.Set("len", Len)
	GlobalSymbolTable.Set("run", Run)
	GlobalSymbolTable.Set("time_stamp", TimeStamp) // 当前的时间戳
}

type SymbolTable struct {
	TableItem map[string]interface{} // 表的所有元素都在这个里面
	Symbols   map[string]interface{} // 所有的symbol
	Parent    *SymbolTable           // 父的symbolTable
}

// 实例化
func NewSymbolTable(parent *SymbolTable) *SymbolTable {
	temp := &SymbolTable{}
	temp.InitSymbolTable(parent)
	return temp
}

// 初始化
func (temp *SymbolTable) InitSymbolTable(parent *SymbolTable) {
	// 初始化一个切片
	temp.Symbols = make(map[string]interface{})
	temp.Parent = parent
}

// 初始化
func (temp *SymbolTable) Get(name string) interface{} {
	value := temp.Symbols[name]
	if value == nil && temp.Parent != nil {
		return temp.Parent.Get(name)
	}
	return value
}

// 设置
func (temp *SymbolTable) Set(name string, value interface{}) {
	temp.Symbols[name] = value
}

// 移除
func (temp *SymbolTable) Remove(name string) {
	delete(temp.Symbols, name)
}
